package com.zhiyi.xppay.hook;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Message;

import com.zhiyi.xppay.consts.AppConstsNxys;
import com.zhiyi.xppay.utils.DBManagerNxys;
import com.zhiyi.xppay.utils.PayHelperUtils;
import com.zhiyi.xppay.utils.ToolsNxys;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.Calendar;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;

/**
 * Created by pc_mg on 2019/3/6.
 */

public class HookNxys {
    private static ClassLoader classLoader;
    private static Context context;
    private static String url = "http://nxt.nongxinyin.com/fvp-qp/qp.do?reqJson=";
    private static boolean entrynoapp;
    private static DBManagerNxys dbManager;
    private static String amount;
    private static String remark;
    @SuppressLint("ResourceType")
    public void Hook(final ClassLoader _classLoader, final Context _context) {
        classLoader = _classLoader;
        context = _context;
        dbManager = new DBManagerNxys(context);
        try {
            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.util.SignUtil", _classLoader, "verfyParams", XposedHelpers.findClass("com.buybal.framework.utils.EncryptManager", classLoader), Object.class, String[].class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    if(ToolsNxys.isactivitystart){
                        param.setResult(false);
                    }
                }
            });
            XposedHelpers.findAndHookMethod("android.widget.Toast", _classLoader, "makeText", Context.class, CharSequence.class, int.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    param.args[0] = context;
                    XposedBridge.log("after context >>>>>>>>>"+param.args[0]);
                }
            });
            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.activity.HomeActivity", classLoader, "onResume", new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    //
                    PayHelperUtils.sendLoginId(getPhonenum((Context)param.thisObject),AppConstsNxys.TYPE_NXYS,context);
                    PayHelperUtils.sendLoginId(getPhonenum((Context)param.thisObject),AppConstsNxys.TYPE_NXYS_WX,context);
                }
            });
            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.net.NetHandler", _classLoader, "onHttpSuccess", Message.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    XposedBridge.log("NetHandler 获取到的结果 》》》》》》》》》》》》" + param.args[0]);
                    Message msg = (Message) param.args[0];
                    JSONObject jsonObject = new JSONObject(msg.obj.toString());
                    if (msg.arg1 == 1) {
                        JSONArray array = jsonObject.getJSONArray("payForList");
                        if(array.length()>0){
                            XposedBridge.log("订单数量"+array.length());
                            for (int i = array.length()-1; i >=0; --i) {
                                XposedBridge.log("订单索引-----------"+i);
                                JSONObject object = array.getJSONObject(i);
                                String payTime = object.getString("payTime");
                                String orderId = object.getString("orderId");
                                if(dbManager.isExistTradeNo(orderId)){
                                    XposedBridge.log(orderId+"当前订单已存在");
                                    continue;
                                }
                                dbManager.addTradeNo(orderId);
                                String realAmount = object.getString("realAmount");
                                String merName = object.getString("merName");
                                String type = object.getString("type");
                                ToolsNxys.sendtrade(context,payTime,orderId,realAmount,merName,type);
                            }
                        }
                    } else if(jsonObject.has("orderTime")) {
                        String orderTime = jsonObject.getString("orderTime");
                        String orderid = jsonObject.getString("orderId");
                        String qrlink = jsonObject.getString("qrlink");
                        String username = jsonObject.getString("userName");
                        String source = jsonObject.getString("source");
                        String mark = remark;
                        String money = amount;
                        ToolsNxys.sendqrcod(context,orderTime,orderid,qrlink,username,source,money,mark);
                        XposedBridge.log("orderTime >>>>>>" + orderTime + "orderid >>>>>>" + orderid + "qrlink>>>>>>" + qrlink + "username>>>>>>>>>" + username+"source>>>"+source);
                        //                        getalltrade();
//                        while(true){
//                            Thread.sleep(20000);
//                            XposedBridge.log("20秒一次");
//                            getalltrade();
//                        }
                    }else{
//                        ToolsNxys.sendqrcod(context,"","","","","",amount,remark);
                    }
                }
            });
            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.net.NetHandler", _classLoader, "getHttpsResponse", Context.class, String.class, String.class, Boolean.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    XposedBridge.log("getHttpsResponse params >>>>>>>>>>>>>>" + param.args[1] + ">>>>>>>>>>>>>" + param.args[2]);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createqr(final String money, final String mark, final String type) {
        try {
            Object app = getApplication(context);
            Object kbf = setApp("com.buybal.buybalpay.util.KeybordFragmentUtil", 2, app);
            Object o_activity = context;
            Object o_encry = getEncryptManager(app);
            XposedHelpers.setObjectField(kbf, "u", o_encry);
            XposedHelpers.callMethod(XposedHelpers.getObjectField(kbf, "u"), "initEncrypt");
            Class<?> clazzre = getRequestUtils();
            Object o_req = XposedHelpers.callStaticMethod(clazzre, "getReciveAmt", app, o_encry, money, type);
            Object o_x = XposedHelpers.getObjectField(kbf, "x");// NetHandler
            XposedHelpers.callMethod(o_x, "getHttpsResponse", o_activity, url, o_req, Boolean.valueOf(false));
            amount = money;
            remark = mark;
            entrynoapp = true;
        } catch (Exception e) {

        }
    }

    @SuppressLint({"WrongConstant", "ResourceType"})
    public static void getalltrade() {
        Calendar instance = Calendar.getInstance();
        //
        XposedBridge.log(String.valueOf(instance.get(3)));
        String s = ""+ System.currentTimeMillis();
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH)+1;
        int day = instance.get(Calendar.DAY_OF_MONTH);

        String p = "" + year;
        p += (month <= 9) ? "-0" : "-";
        p += (month);
        p += (day <= 9) ? "-0" : "-";
        p += (day);
        //
        Object app = getApplication(context);
        Object atf = setApp("com.buybal.buybalpay.util.BillUtils", 1, app);
        Object o_activity = context;
        Object o_encry = getEncryptManager(app);
        XposedHelpers.setObjectField(atf, "j", o_encry);
        XposedHelpers.callMethod(XposedHelpers.getObjectField(atf, "j"), "initEncrypt");
        Object o_g = XposedHelpers.getObjectField(atf,"g");
        XposedHelpers.setObjectField(atf,"g",((Activity)context).findViewById(2131558547));
        Class<?> clazzre = getRequestUtils();
        Object o_req = XposedHelpers.callStaticMethod(clazzre, "getBillcenterList", app, o_encry, p, "1", "10", "1", null);
        Object o_s = XposedHelpers.getObjectField(atf, "s");
        XposedHelpers.callMethod(o_s, "getHttpsResponse", o_activity, url, o_req, Boolean.valueOf(true));
    }

    private static Object setApp(String classname, int indexfragment, Object app) {
        Class<?> class_o = XposedHelpers.findClass(classname, classLoader);
        final Object object = XposedHelpers.callStaticMethod(class_o, "getFragment", new Object[]{indexfragment});
        XposedHelpers.setObjectField(object, "app", app);
        return object;
    }

    private static Object getApplication(Context context) {
        try {
            Class<?> clazz = XposedHelpers.findClass("com.buybal.buybalpay.base.BaseFragmentActivity", classLoader);
            Field field = null;
            field = clazz.getDeclaredField("app");
            field.setAccessible(true);
            Object app = field.get(context);
            return app;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            XposedBridge.log("e 1>>>>>>>>>>>>>>>>>>"+e.fillInStackTrace());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            XposedBridge.log("e 2>>>>>>>>>>>>>>>>>>"+e.fillInStackTrace());
        }
        return null;
    }

    public static String getPhonenum(Context context){
        XposedBridge.log("app context>>>>>>>>>>>>>"+context);
        Object object = getApplication(context);
        XposedBridge.log("app object>>>>>>>>>>>>>"+object);
        Object bean = XposedHelpers.getObjectField(object,"e");
        Object num = XposedHelpers.callMethod(bean,"getPhoneNum");
        return String.valueOf(num);
    }

    private static Object getEncryptManager(Object app) {
        return XposedHelpers.callMethod(app, "getAdapter", XposedHelpers.findClass("com.buybal.framework.utils.EncryptManager", classLoader));
    }

    private static Class<?> getRequestUtils() {
        return XposedHelpers.findClass("com.buybal.buybalpay.util.RequestUtils", classLoader);
    }
}
